package com.lenovo.mso2o.ui;

import android.Manifest;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FileHelper;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.conf.OrderAction;
import com.lenovo.mso2o.entity.FAttachment;
import com.lenovo.mso2o.entity.FileRequest;
import com.lenovo.mso2o.entity.OrderUpdatingRequest;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.OtherAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.service.UploadService;
import com.lenovo.mso2o.util.ActionCallbacks;
import com.lenovo.mso2o.util.Utils;
import com.lenovo.mso2o.view.widget.MySurfaceView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by lenovo on 2016/3/11.
 */
public class SignInCameraActivity extends FBaseActivity {
    private Button btn_camera_capture = null;
    private Button btn_camera_cancel = null;
    private Button btn_camera_ok = null;
    private Button btn_front_back_camera = null;
    private OtherAPI api = null;
    private Camera camera = null;
    private MySurfaceView mySurfaceView = null;
    private Subscription _subscription;
    private int CameraType = 1;//0代表后置摄像头，1代表前置摄像头
    private byte[] buffer = null;

    private final int TYPE_FILE_IMAGE = 1;
    private final int TYPE_FILE_VEDIO = 2;
    private String example_plain = "";
    private String ticketId;
    private String photoPathInSd = "";

    private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            if (!TextUtils.isEmpty(photoPathInSd)) {
                new File(photoPathInSd).delete();
            }
            FileHelper.ensureDir(MSApplication.getDataDir() + "/image/");
            photoPathInSd = MSApplication.getDataDir() + "/image/" + "IMG_" + System.currentTimeMillis() + ".jpg";
            ///storage/emulated/0/mso2o/image/1459995942607.jpg
            ///storage/emulated/0/Pictures/com.lenovo.mso2o/IMG_1459996158881.jpg
            DLog.w("pic", "length:" + (data == null ? 0 : data.length));
            savePicture(data, new File(photoPathInSd));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mycamera_layout);
        ticketId = getIntent().getStringExtra("ticketid");
        btn_camera_capture = (Button) findViewById(R.id.camera_capture);
        btn_camera_ok = (Button) findViewById(R.id.camera_ok);
        //btn_camera_ok.setText(example_plain);
        btn_camera_ok.setText(example_plain);
        btn_camera_cancel = (Button) findViewById(R.id.camera_cancel);
        //btn_camera_cancel.setText(cancel_plain);
        btn_camera_cancel.setText(getString(R.string.cancel_plain));
        btn_front_back_camera = (Button) findViewById(R.id.bt_front_back_camera);
        //api = ServiceGenerator.createService(OtherAPI.class, MSConstants.APIConstants.APISERVER_ADDRESS + url.substring(1, 1 + url.lastIndexOf("/")));
        btn_front_back_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//调整前后摄像头
                if (CameraType == 1) {//当前为前置
                    CameraType = 0;
                    camera.stopPreview();//停掉原来摄像头的预览
                    camera.release();//释放资源
                    camera = null;//取消原来摄像头
                    camera = Camera.open(CameraType);//打开当前选中的摄像头

                    try {
                        camera.setPreviewDisplay(mySurfaceView.getHolder());//通过surfaceview显示取景画面
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    camera.setDisplayOrientation(90);
                    camera.startPreview();//开始预览
                } else {
                    CameraType = 1;
                    camera.stopPreview();//停掉原来摄像头的预览
                    camera.release();//释放资源
                    camera = null;//取消原来摄像头
                    camera = Camera.open(CameraType);//打开当前选中的摄像头
                    try {
                        camera.setPreviewDisplay(mySurfaceView.getHolder());//通过surfaceview显示取景画面
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    camera.setDisplayOrientation(90);
                    camera.startPreview();//开始预览
                }

            }
        });
        btn_camera_capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                camera.takePicture(mShutterCallback, new Camera.PictureCallback() {

                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {

                    }
                }, pictureCallback);
                btn_camera_capture.setVisibility(View.INVISIBLE);
                btn_camera_ok.setText(getString(R.string.use_photo_plain));
                btn_camera_cancel.setText(getString(R.string.capture_again_plain));
                btn_camera_ok.setVisibility(View.VISIBLE);
                btn_camera_cancel.setVisibility(View.VISIBLE);
            }
        });
        btn_camera_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                /*saveImageToFile();
                camera.startPreview();
				btn_camera_capture.setVisibility(View.VISIBLE);
				btn_camera_ok.setVisibility(View.INVISIBLE);
				btn_camera_cancel.setVisibility(View.INVISIBLE);*/
                String ok_str = btn_camera_ok.getText().toString();
                if (example_plain.equals(ok_str)) {

                } else if (getString(R.string.use_photo_plain).equals(ok_str)) {
                    btn_camera_ok.setClickable(false);
                    //手动签到并上传照片
                    //手动签到
                    OrderUpdatingRequest signRequest = new OrderUpdatingRequest();
                    //由于自动签到和手动签到要作区分，所以新给的参数{"fields":{"signtype":0}}表示自动签到
                    Map<String, Integer> mMap = new HashMap<>();
                    signRequest.setFields(mMap);
                    ServiceGenerator.createService(OrderAPI.class)
                            .updateOrder(ticketId, OrderAction.SIGININ.getValue(), signRequest)
                            // Started in onStart(), running until in onStop()
                            //.compose(webFragment.<Res>bindUntilEvent(FragmentEvent.DESTROY))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .unsubscribeOn(Schedulers.io())
                            .doOnTerminate(new Action0() {
                                @Override
                                public void call() {
                                }
                            })
                            .subscribe(new NetworkObserver<Res>() {
                                @Override
                                public void onSuccess(Res result) {
                                    //webActivity.processDismiss();
                                    if (result.getEcode() != 0) {
                                        Toast.makeText(SignInCameraActivity.this, "签到失败", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(SignInCameraActivity.this, "签到成功", Toast.LENGTH_SHORT).show();
                                        //刷新页面
                                        List<Activity> activityList = FBaseActivity.getActivites();
                                        for (Activity a : activityList) {
                                            if (a instanceof MainActivity) {
                                                ((MainActivity) a).onPageSelected(MainActivity.PAGE_ACTIVE_ORDER, true);
                                            } else {
                                                ((FBaseActivity) a).setResult(Activity.RESULT_CANCELED);
                                                ((FBaseActivity) a).defaultFinish();
                                            }
                                        }
                                    }
                                    //上传照片
                                    sendPhoto2Server();
                                    //("tickets/{ticketid}/{action}")
                                    String action = "/tickets/" + ticketId + "/" + OrderAction.SIGININ.getValue();
                                    ActionCallbacks.uploadInfoAsync(SignInCameraActivity.this, action);
                                    finish();
                                }

                                @Override
                                public void onFailure(String tip) {
                                    //webActivity.processDismiss();
                                    Toast.makeText(SignInCameraActivity.this, "签到失败", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            });
                }
            }
        });
        btn_camera_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_camera_ok.setClickable(true);

                String cel_str = btn_camera_cancel.getText().toString();
                if (getString(R.string.cancel_plain).equals(cel_str)) {
                    finish();
                } else if (getString(R.string.capture_again_plain).equals(cel_str)) {
                    camera.startPreview();
                    btn_camera_capture.setVisibility(View.VISIBLE);
                    btn_camera_ok.setVisibility(View.VISIBLE);
                    btn_camera_ok.setText(example_plain);
                    btn_camera_cancel.setVisibility(View.VISIBLE);
                    btn_camera_cancel.setText(getString(R.string.cancel_plain));
                }

            }
        });
    }

    private void sendPhoto2Server() {
        String url = "/tickets/" + ticketId + "/attachments/info";
        OtherAPI api = ServiceGenerator.createService(OtherAPI.class, MSConstants.APIConstants.APISERVER_ADDRESS + url.substring(1, 1 + url.lastIndexOf("/")));
        FileRequest fileRequest = new FileRequest();
        String pathRequest = "android_file://" + photoPathInSd + "?2";
        fileRequest.getOriginal().add(pathRequest);
        Observable<Res<String[]>> filecall = api.dynamicPostRxFile(url.substring(url.lastIndexOf("/") + 1), fileRequest);

        final ArrayList<FAttachment> uploads = new ArrayList<>();
        FAttachment a = new FAttachment();
        a.setPath(photoPathInSd);
        uploads.add(a);
        _subscription = filecall
                // Started in onStart(), running until in onStop()
                .subscribeOn(Schedulers.io())
                .map(new Func1<Res<String[]>, Res<String[]>>() {
                    @Override
                    public Res<String[]> call(Res<String[]> res) {
                        return res;
                    }
                })
                .doOnTerminate(new Action0() {
                    @Override
                    public void call() {
                        _subscription = null;
                    }
                })
                .subscribe(new NetworkObserver<Res<String[]>>() {
                    @Override
                    public void onSuccess(Res<String[]> result) {
                        if (result.getEcode() == 0) {
                            for (FAttachment a : uploads) {
                                a.setLazyId(result.getResult()[0]);
                                a.setTicketid(ticketId);
                                a.setAction(OrderAction.SIGININ.getValue());
                            }
                            if (uploads.size() > 0) {
                                UploadService.actionLocalAttachInsert(SignInCameraActivity.this, uploads);
                            }
                        }
                    }

                    @Override
                    public void onFailure(String tip) {
                    }
                });
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if(camera != null)
        camera.release();
        camera = null;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();

        requestPermission(Manifest.permission.CAMERA, new Runnable() {
            @Override
            public void run() {
                if (ContextCompat.checkSelfPermission(SignInCameraActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(SignInCameraActivity.this, "无法调用摄像头，请到工单详情页完成签到", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    if (camera == null) {
                        camera = getCameraInstance();
                        if (camera != null) {
                            camera.setDisplayOrientation(90);
                        } else {
                            Toast.makeText(SignInCameraActivity.this, "无法调用摄像头，请到工单详情页完成签到", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        mySurfaceView = new MySurfaceView(getApplicationContext(), camera);
                        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
                        preview.addView(mySurfaceView);
                    }
                }
            }
        });

        /*if (camera == null) {
            camera = getCameraInstance();
            if(camera != null) {
                camera.setDisplayOrientation(90);
            }else{
                Toast.makeText(this, "无法调用摄像头，请到工单详情页完成签到", Toast.LENGTH_SHORT).show();
                finish();
            }
            mySurfaceView = new MySurfaceView(getApplicationContext(), camera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mySurfaceView);
        }*/
    }

    private Camera getCameraInstance() {
        Camera camera = null;
        try {//1 前置摄像头，0后置摄像头
            camera = Camera.open(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return camera;
    }

    /*为了实现拍照的快门声音及拍照保存照片需要下面三个回调变量*/
    Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback()
            //快门按下的回调，在这里我们可以设置类似播放“咔嚓”声之类的操作。默认的就是咔嚓。
    {
        public void onShutter() {
            // TODO Auto-generated method stub
        }
    };

    @Override
    protected void onDestroy() {
        camera = null;
        if (_subscription != null) {
            _subscription.unsubscribe();
        }
        super.onDestroy();
    }

    /*
    * created savePicture(byte [] data) for testing
    */
    public void savePicture(byte[] data, File pictureFile) {
        DLog.d("ScanVinFromBarcodeActivity ", "savePicture(byte [] data)");
        try {
            if (!pictureFile.exists()) {
                pictureFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();

            DLog.i("saved", "New Image saved:" + pictureFile.getAbsolutePath());

        } catch (Exception error) {
            DLog.p(error);
            DLog.d("File not saved: ", error.getMessage());
        }
    }

}

